package sentinel

import (
	"github.com/garyburd/redigo/redis"
	"log"
	"rhelper"
	"time"
)

func MonitorRedis() {
	ticker := time.NewTicker(2 * time.Minute)
	for {
		select {
		case <-ticker.C:
			checkRedisRole()
		}
	}
}

func checkRedisRole() {
	rconn := rhelper.Pool().Get()
	defer rconn.Close()

	res, err := rconn.Do("ROLE")
	if err != nil {
		log.Println("err: ", err)
	}

	rres, ok := res.([]interface{})
	if !ok {
		log.Println("get role failed")
		return
	}

	role, err := redis.String(rres[0], nil)
	if err != nil {
		log.Println("get role failed")
		return
	}

	if role != "master" {
		log.Println("redis role is not master, do recovery")
		go doRecovery()
	}

	// log.Println("role: ", role)

}
